# -*- coding: utf-8 -*-
# Copyright 2011-2012 MagiCycles.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from django.http import HttpResponseRedirect,HttpResponse
from django.views.decorators.cache import never_cache

from siteutils import render_to_response,render_to_javasript
from siteutils import requires_site_admin,errorpage,post_activity_to_outsite,requires_site_user
from siteutils.units import save_current_units
from siteutils.language import _,save_current_lang

from apis import outusers,people_api,stats_api,routes_api

@never_cache
def login(request):
    login_url = request.build_absolute_uri("/login/")
    context = {"loginurls": outusers.create_login_urls(login_url)}
    return render_to_response("login.html", context)

@never_cache
def outsitelogin(request, outsite):
    if outsite not in outusers.OutSitesTypes:
        return errorpage(_("unknown login site"))

    #outsite_callback = request.build_absolute_uri("/riders/join/?site=%s"%outsite)
    outsite_callback = "http://www.magicycles.com/riders/join/?site=%s"%outsite
    return HttpResponseRedirect(outusers.create_auth_url(outsite, outsite_callback))

@never_cache
def connectoutsite(request, outsite):
    if not outsite:  # callback handler
        user = people_api.get_current_user()
        if not user:
            return errorpage("You must login first")

        outsite = request.GET.get("site", None)
        if outsite not in outusers.OutSitesTypes:
            return errorpage(_("unknown login site"))

        try:
            if not outusers.bind_outsite(request, user, outsite):
                return errorpage("Connect to %s failed, pls retry"%(outsite))
            outusers.refresh_outsite_user()
        except Exception,e:
            return errorpage(str(e))

        return HttpResponseRedirect("/riders/%s/editprofile/"%(user.uid))

    # get outsite auth, callback to this view
    if outsite not in outusers.OutSitesTypes:
        return errorpage(_("unknown login site"))

    #outsite_callback = request.build_absolute_uri("/connect/?site=%s"%outsite)
    outsite_callback = "http://www.magicycles.com/connect/?site=%s"%outsite
    return HttpResponseRedirect(outusers.create_auth_url(outsite, outsite_callback))

@never_cache
def logout(request):
    return outusers.logout(request)


def do_queue(request, action):
    if action == "post_activity":
        outsite_uid = request.POST.get("uid", None)
        activity_id = request.POST.get("activity_id", None)
        if outsite_uid and activity_id:
            post_activity_to_outsite(outsite_uid, activity_id)
    return HttpResponse()


@never_cache
def localjavascript(request, scriptname):
    return render_to_javasript(scriptname,{})

def indevelop(request):
    return errorpage(_("in developing..."))

def index(request):
    lang = request.GET.get("lang",None)
    if lang:
        user = people_api.get_current_user()
        if user:
            people_api.save_user_profile(user.uid, { "language" : lang })
        save_current_lang(lang)
        return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))

    unit = request.GET.get("unit",None)
    if unit:
        user = people_api.get_current_user()
        if user:
            people_api.save_user_profile(user.uid, { "units" : unit })
        save_current_units(unit)
        return HttpResponseRedirect(request.META.get('HTTP_REFERER','/'))
        
    context = {"option": {"enable_gmap":True,},
               "stats":stats_api.get_stats(),
               }
    return render_to_response("index.html", context)

def search(request):
    pagesize_route = 10
    pagesize_rider = 20
    pagesize_comment = 20
    context = {"pagesize": {"riders":pagesize_rider,
                            "routes":pagesize_route,
                            "comments": pagesize_comment},
               "riders": [],
               "routes": [],}
    if request.method == "POST":
        from siteutils import escape_and_strip
        #search_text = escape_and_strip(request.POST.get("search-txt",""))
        search_text = request.POST.get("search-txt","").strip()
        context["search_text"] = search_text
        search_text = escape_and_strip(search_text)
        search_list = search_text.split(" ")
        length = max([len(word.strip()) for word in search_list])
        if length > 1:
            rider_cursor = request.POST.get("rider_cursor","").strip()
            results = people_api.search_riders(request, search_text, pagesize=pagesize_rider, start_cursor=rider_cursor)
            context["riders"] = results["riders"]
            context["rider_cursor"] = results["end_cursor"]

            route_cursor = request.POST.get("route_cursor","").strip()
            results = routes_api.search_routes(request, search_text, pagesize=pagesize_route, start_cursor=route_cursor)
            context["routes"] = results["routes"]
            context["route_cursor"] = results["end_cursor"]

    return render_to_response("search.html", context)

def upload(request):
    context = {}
    return render_to_response("upload.html", context)

def donate(request):
    context = {}
    return render_to_response("donate.html", context)

def tos(request):
    context = {}
    return render_to_response("tos.html", context)

def error404(request):
    return errorpage(_("404 Page not found"))

def error500(request):
    return errorpage(_("500 Server Error"))

def main():
    pass

if __name__ == '__main__':
    main()
